package com.ywjt.platformbusiness.my.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.BaseModel;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.login.model.LoginModel;
import com.ywjt.platformbusiness.my.adapter.AddressAdapter;
import com.ywjt.platformbusiness.my.model.AddressModel;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ywjt.platformbusiness.common.MethodUtils.getUserId;


public class ActivityAddress extends BaseActivity implements View.OnClickListener {

    private TextView tvAdd;
    private LinearLayout llNodata;
    private RecyclerView rcAddress;
    private AddressAdapter addressAdapter;
    private SmartRefreshLayout refesh;
    private int count = 0;
    private int type=0;
    private  AddressModel   addressModel;

    public static void actionStart(Context context,int type) {
        Intent intent = new Intent(context, ActivityAddress.class);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tvAdd:
                //新增收货地址
                ActivityAddAddress.actionStart(getContext());
                break;
        }
    }


    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_address;
    }

    @Override
    protected void initView() {
        setTitleText("收货地址");
        type=getIntent().getIntExtra("type",0);
        tvAdd=findViewById(R.id.tvAdd);
        tvAdd.setOnClickListener(this);
        llNodata=findViewById(R.id.llNodata);
        refesh=findViewById(R.id.refresh);
        rcAddress=findViewById(R.id.rcAddress);
        setView();
    }


    public void setView(){
        refesh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getData();
            }
        });
    }

      //获取地址列表
    public void getData(){
        new HttpRequest(getContext()).doGet(UrlConstants.merchant_getReceivingAddressList, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                    String datas = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(datas);
                        String message = jsonObject.getString("message");
                        Boolean success=jsonObject.getBoolean("success");
                        if(success){
                            Object obj = JsonUtils.fromJson(result.toString(), AddressModel.class);
                            if (obj instanceof AddressModel) {
                                   addressModel=(AddressModel)obj;
                                    if (addressModel.getResult().size() > 0) {
                                        llNodata.setVisibility(View.GONE);
                                        rcAddress.setVisibility(View.VISIBLE);
                                        tvAdd.setVisibility(View.VISIBLE);
                                        /*****/
                                        addressAdapter=new AddressAdapter(addressModel.getResult());
                                        rcAddress.setLayoutManager(new LinearLayoutManager(getContext()));
                                        rcAddress.setAdapter(addressAdapter);
                                        addressAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                            @Override
                                            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                                switch (view.getId()) {
                                                    case R.id.tvEdit:
                                                        //修改收货地址
                                                         ActivityAddAddress.actionStart(getContext(),1,addressModel.getResult().get(position));
                                                        break;
//                                        case R.id.tvDel:
//                                            WarningDialog dialog=new WarningDialog(ActivityAddress.this,
//                                                    "确定要删除该地址吗？","取消","删除","");
//                                           dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
//                                               @Override
//                                               public void doCancel() {
//                                                   dialog.dismiss();
//                                               }
//
//                                               @Override
//                                               public void doConfirm() {
//                                                   dialog.dismiss();
//                                                   deleteAddress(String.valueOf(data.get(position).getId()));
//                                               }
//                                           });
//                                            dialog.show();
//                                            break;
                                                    case R.id.ivSelect:
                                                        //设为默认地址
                                                        updateAddress(position);
                                                        break;
                                                }
                                            }
                                        });

                                        addressAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                            @Override
                                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                                if (type==1){
                                                    //没有item点击事件
                                                    return;
                                                }else {
                                                    Intent intent = new Intent();
                                                    intent.putExtra("userAddressId",addressModel.getResult().get(position).getId()+"");
                                                    intent.putExtra("name", addressModel.getResult().get(position).getName());
                                                    intent.putExtra("phone",addressModel.getResult().get(position).getPhone());
                                                    intent.putExtra("isDefault",addressModel.getResult().get(position).getIsDefault());
                                                    intent.putExtra("detailaddress",addressModel.getResult().get(position).getDetailAddress());
                                                    intent.putExtra("address",addressModel.getResult().get(position).getAddress());
                                                    setResult(RESULT_OK, intent);
                                                    finish();
                                                }
                                            }
                                        });
                                        /****/
                                        if (addressAdapter.getItemCount() < count) {
                                            //还有多的数据
                                            refesh.finishRefresh();
                                        } else {
                                            //没有更多数据（上拉加载功能将显示没有更多数据）
                                            refesh.finishRefreshWithNoMoreData();
                                        }
                                    } else {
                                        rcAddress.setVisibility(View.GONE);
                                        refesh.finishRefreshWithNoMoreData();
                                        llNodata.setVisibility(View.VISIBLE);
                                        tvAdd.setVisibility(View.GONE);
                                    }

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
            }

            @Override
            public void onFailure(int code, String msg) {
                refesh.finishLoadMore();
                refesh.finishRefresh();
            }
        });
    }

    //修改地址update
    public void updateAddress(int posi){
        new HttpRequest(getContext()).doPost(UrlConstants.updateDefaultAddress+addressModel.getResult().get(posi).getId(), "",new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;

                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        getData();
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }

}
